package com.oig.sys.msg.controller;

import com.oig.common.exception.BadRequestException;
import com.oig.common.module.SysResponse;
import com.oig.common.validator.GroupAdd;
import com.oig.sys.log.annotation.SysLog;
import com.oig.sys.msg.app.IAppMqMsgService;
import com.oig.sys.msg.dto.MqMsgDto;
import com.oig.sys.msg.entity.TbMqMsg;
import com.oig.sys.msg.service.ITbMqConfigService;
import com.oig.sys.msg.vo.MqConfigVo;
import com.oig.sys.msg.vo.MqMsgVo;
import io.swagger.v3.oas.annotations.Hidden;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * mq消息表
 * 发送前都往消息表里存，保证事务（由分布式事务框架保证）
 * 发送后如果未发送成功，可以再补发
 * 考虑只给超级管理员用
 */
@Tag(name = "mq消息查询")
@RestController
@RequestMapping("/mqMsg")
@Slf4j
@RequiredArgsConstructor
public class TbMqMsgController {

    private final IAppMqMsgService appMqMsgService;
    private final ITbMqConfigService mqConfigService;
    private final RabbitTemplate rabbitTemplate;

    @Hidden
    @Operation(summary = "添加mq消息内容")
    @PostMapping(value = "/add")
    public MqMsgVo addMqMsg(@RequestBody @Validated(GroupAdd.class) MqMsgDto mqMsgDto){
        log.info("add mq msg, {}", mqMsgDto);
        return this.appMqMsgService.addMqMsg(mqMsgDto);
    }


    /**
     * 手工发送
     */
    @PreAuthorize("@pms.hasPermission('/mqMsg/sendMq')")
    @SysLog(value="手工发送",apiUrl="/mqMsg/sendMq")
    @Operation(summary = "手工发送,不管状态，强制发送")
    @PostMapping(value = "/sendMq/{msgId}")
    public SysResponse<Integer> sendMq(@PathVariable("msgId") Integer msgId){
        TbMqMsg mqMsg = appMqMsgService.getMqMsg(msgId) ;
        if (mqMsg==null){
            throw new BadRequestException("消息不存在") ;
        }
        if (mqMsg.getSendFlag()==null){
            throw new BadRequestException("消息未准备");
        }
        MqConfigVo mqConfig = mqConfigService.getOkMqConfig(mqMsg.getRelationType()) ;
        if (mqConfig==null){
            throw new BadRequestException("mq配置不存在") ;
        }
        rabbitTemplate.convertAndSend(mqConfig.getProducerExchange(), mqConfig.getProducerKey(), mqMsg.getMsgContent());
        this.appMqMsgService.moveMsgToHis(mqMsg); //发了就挪历史表
        return SysResponse.ok(msgId, "发送成功");
    }




}
